package com.xh.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xh.ssm.bean.Role;
import com.xh.ssm.bean.Userinfo;
import com.xh.ssm.mapper.RoleMapper;
import com.xh.ssm.mapper.UserinfoMapper;
import com.xh.ssm.service.RoleService;
import com.xh.ssm.util.R;
import com.xh.ssm.util.RTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author PangJunjie
 * @Date 2024/1/26/026
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserinfoMapper userinfoMapper;

    public R getPage(int page, int limit, Role role) {
        /*在查询的前一行调用startPage方法，即可自动完成分页*/
        PageHelper.startPage(page, limit);
        List<Role> list = roleMapper.getList(role);
        PageInfo<Role> pageInfo = new PageInfo<Role>(list);
        return R.page(pageInfo.getTotal(), pageInfo.getList());
    }

    public Role getById(int id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(Role role) {
        if (role.getId() == null) {
            roleMapper.insertSelective(role);
        } else {
            roleMapper.updateByPrimaryKeySelective(role);
        }
    }

    public void deleteById(int id) {
        Userinfo userinfo = new Userinfo();
        userinfo.setRoleId(id);
        if (userinfoMapper.getList(userinfo).isEmpty()) {
            roleMapper.deleteByPrimaryKey(id);
        } else {
            throw new RTException("该角色已被使用，禁止删除！");
        }

    }

    public R getList() {
        return R.ok(roleMapper.getList(new Role()));
    }
}
